package com.dhms.vostok1.ui.login

import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.res.ResourcesCompat
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import com.dhms.lib.app.LibApplication
import com.dhms.vostok1.R
import com.dhms.vostok1.databinding.ActivityLoginBinding
import com.dhms.vostok1.model.SettingViewModel
import com.dhms.vostok1.model.UserViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class LoginActivity : AppCompatActivity() {

    private lateinit var _binding: ActivityLoginBinding
    val binding get() = _binding

    private lateinit var navController: NavController

    private val userViewModel: UserViewModel by viewModels()
    private val settingViewModel: SettingViewModel by viewModels()

    private var preToastCoroutine: Job? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        _binding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val navHostFragment =
            supportFragmentManager.findFragmentById(R.id.nav_login_fragment) as NavHostFragment
        navController = navHostFragment.navController

        navController.addOnDestinationChangedListener { _, _, _ ->
            userViewModel.clearApiResults()
        }

        userViewModel.setContextAndSharePref(
            this,
            LibApplication.mmkv
        )
        settingViewModel.setSharedPreferences(
            LibApplication.mmkv
        )
        settingViewModel.getSettings()
    }

    fun showToast(
        icon: Int? = null,
        message: String? = null,
        isLoading: Boolean = false,
        timeOut: Int = 3,
        isShowing: Boolean = true
    ) {
        if (icon != null) {
            binding.toast.icon = ResourcesCompat.getDrawable(resources, icon, null)
        }
        binding.toast.message = message
        binding.toast.isLoading = isLoading
        binding.toast.visibility = isShowing
        // 把之前的协程取消，以免之前的取消动作影响当前toast
        preToastCoroutine?.cancel()
        if (timeOut != 0) {
            preToastCoroutine = lifecycleScope.launch {
                delay(timeOut * 1000L)
                binding.toast.visibility = false
            }
        } else {
            // 常驻的没有协程对其关闭，把pre协程Job置null
            preToastCoroutine = null
        }
    }

    fun hideToast() {
        preToastCoroutine?.cancel()
        binding.toast.visibility = false
        preToastCoroutine = null
    }
}